package com.chb.mains;

/**
 * @author CHB
 * @createTime 2022-7-5 11:10
 */
public class AddTwoNums {

    public static void main(String[] args) {
        // l1 = [2,4,3], l2 = [5,6,4]
        AddTwoNums addTwoNums = new AddTwoNums();
        ListNode l1 = addTwoNums.generateList(new int[]{9,9,9,9,9,9,9});
        ListNode l2 = addTwoNums.generateList(new int[]{9,9,9});
        ListNode node = addTwoNums.addTwoNumbers(l1, l2);
        System.out.println(node);

    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 进位标志
        int temp = 0;
        ListNode result =  new ListNode();
        ListNode resultCur = result;
        while(true){
            int num1 = 0;
            int num2 = 0;
            if(l1 == null && l2 == null && temp == 0){
                break;
            }
            if(l1 != null){
                num1 = l1.val;
                l1 = l1.next;
            }
            if(l2 != null){
                num2 = l2.val;
                l2 = l2.next;
            }
            int num3 = num1 + num2 + temp;
            if(num3 >= 10){
                num3 = num3%10;
                temp = 1;
            }else{
                temp = 0;
            }
            resultCur.next = new ListNode(num3);
            resultCur = resultCur.next;
        }
        return result.next;
    }
    // 生成链表
    private ListNode generateList(int []nums){
        ListNode listNode = new ListNode();
        ListNode c = listNode;
        for (int num : nums) {
            ListNode node = new ListNode(num);
            c.next = node;
            c = node;
        }
        return listNode.next;
    }
}
